import requests
import json
from datetime import datetime
import time
import pandas as pd
import argparse
from typing import List, Dict, Optional

# 配置信息
config = {
    "shop_url": "s-fashionicon.myshopify.com/",
    "api_version": "2025-07",
    "location_id": 79893692710,  # 仓库ID
    "default_customer_email": "songyuchen.alex@gmail.com",
    "default_shipping_carrier": "FedEx",
    "excel_file_path": "AI造数.xlsx",  # 默认Excel文件路径
    "sheet_name": "aftership"  # Excel工作表名称，对应access_token表中的表头
}


def get_access_token(file_path: str) -> Optional[str]:
    """从Excel的access_token工作表读取对应的access token"""
    try:
        # 读取access_token工作表
        df = pd.read_excel(file_path, sheet_name="access_token", header=0)

        # 检查是否存在与当前sheet_name匹配的列
        if config["sheet_name"] not in df.columns:
            print(f"❌ 在access_token工作表中未找到'{config['sheet_name']}'列")
            return None

        # 获取该列的第一个值
        access_token = df[config["sheet_name"]].iloc[0]

        if pd.notna(access_token) and str(access_token).startswith("shpat_"):
            return str(access_token)
        else:
            print(f"❌ 从access_token工作表获取的token无效: {access_token}")
            return None

    except Exception as e:
        print(f"❌ 读取access_token失败: {e}")
        return None


def create_order(line_items: List[Dict], access_token: str) -> Optional[Dict]:
    """创建单个订单"""
    timestamp = int(time.time())
    tracking_number = f"TEST{timestamp}"

    customer_email = config["default_customer_email"]

    shipping_address = {
        "first_name": "yuchen",
        "last_name": "yuchen",
        "address1": "555 W 32nd St",
        "address2": "Suite 100",
        "city": "New York",
        "province": "New York",
        "country": "United States",
        "zip": "10001",
        "phone": "+1 212-123-4567"
    }

    order_data = {
        "order": {
            "email": customer_email,
            "line_items": line_items,
            "financial_status": "paid",
            "fulfillment_status": "fulfilled",
            "shipping_address": shipping_address,
            "customer": {
                "first_name": "yuchen",
                "last_name": "yuchen",
                "email": customer_email
            },
            "fulfillments": [{
                "location_id": config["location_id"],
                "tracking_number": tracking_number,
                "tracking_company": config["default_shipping_carrier"],
                "tracking_urls": [
                    f"https://www.{config['default_shipping_carrier'].lower()}.com/track?tracknum={tracking_number}"],
                "line_items": [{"variant_id": item["variant_id"], "quantity": item["quantity"]} for item in line_items],
                "status": "success",
                "created_at": datetime.now().isoformat(),
                "updated_at": datetime.now().isoformat()
            }]
        }
    }

    base_url = f"https://{config['shop_url']}/admin/api/{config['api_version']}"
    url = f"{base_url}/orders.json"
    headers = {
        "Content-Type": "application/json",
        "X-Shopify-Access-Token": access_token
    }

    try:
        response = requests.post(url, headers=headers, data=json.dumps(order_data))
        if response.status_code == 201:
            order_info = response.json()['order']
            print(f"✅ 成功创建订单 {order_info['name']} - 追踪号: {tracking_number}")
            return order_info
        else:
            print(f"❌ 失败：状态码{response.status_code}，响应{response.text}")
            return None
    except Exception as e:
        print(f"❌ 错误：{e}")
        return None


def read_orders_from_excel(file_path: str, sheet_name: str) -> List[List[Dict]]:
    """从Excel文件读取订单信息（忽略第一列，从第二列开始解析变体ID和数量）"""
    try:
        # 读取Excel文件，将第一行作为表头
        df = pd.read_excel(file_path, sheet_name=sheet_name, header=0)

        if df.empty:
            raise ValueError("Excel文件为空")

        # 获取列名（变体ID），跳过第一列
        variant_ids = df.columns[1:].tolist()
        variant_ids = [int(vid) for vid in variant_ids if pd.notna(vid)]

        if not variant_ids:
            raise ValueError("Excel文件中没有找到有效的变体ID")

        orders = []
        # 遍历每一行数据（跳过表头）
        for index, row in df.iterrows():
            line_items = []
            for i, variant_id in enumerate(variant_ids):
                # 列索引从1开始（跳过第一列）
                col_name = df.columns[i + 1]
                quantity = row[col_name]
                if pd.notna(quantity) and int(quantity) > 0:
                    line_items.append({
                        "variant_id": variant_id,
                        "quantity": int(quantity)
                    })

            if line_items:
                orders.append(line_items)
                print(f"从Excel读取订单 {index + 1}: {line_items}")
            else:
                print(f"⚠️ 忽略空订单（行 {index + 1}）")

        return orders

    except Exception as e:
        print(f"❌ 读取Excel文件失败: {e}")
        return []


def create_orders_from_excel(file_path: str, sheet_name: str, delay_seconds: int = 15) -> None:
    """从Excel文件创建多个订单"""
    # 先获取access token
    access_token = get_access_token(file_path)
    if not access_token:
        print("无法获取有效的access token，程序退出")
        return

    orders = read_orders_from_excel(file_path, sheet_name)

    if not orders:
        print("没有找到可创建的订单，程序退出")
        return

    print(f"\n开始创建 {len(orders)} 个订单...")
    successes = 0
    failures = 0

    for i, line_items in enumerate(orders):
        print(f"\n📌 正在创建第 {i + 1}/{len(orders)} 个订单...")
        result = create_order(line_items, access_token)

        if result:
            successes += 1
        else:
            failures += 1

        if i + 1 < len(orders):
            print(f"等待 {delay_seconds} 秒后创建下一个订单...")
            time.sleep(delay_seconds)

    print(f"\n📊 订单创建完成：成功 {successes} 个，失败 {failures} 个")


def main():
    parser = argparse.ArgumentParser(description='从Excel文件批量创建Shopify订单')
    parser.add_argument('--file', type=str, default=config["excel_file_path"],
                        help=f'Excel文件路径，默认: {config["excel_file_path"]}')
    parser.add_argument('--sheet', type=str, default=config["sheet_name"],
                        help=f'Excel工作表名称，默认: {config["sheet_name"]}')
    parser.add_argument('--delay', type=int, default=15,
                        help=f'订单创建间隔秒数，默认: 15')

    args = parser.parse_args()
    create_orders_from_excel(args.file, args.sheet, args.delay)


if __name__ == "__main__":
    main()
